package org.dreamwork.assistant.tools.network.gui;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;

/**
 * Created by seth.yang on 2018/5/10
 */
public class TcpClientWorker implements NetworkReader.NetworkReaderListener{
    private Socket socket;
    String name;

    private OutputStream out;
    private TcpReader reader;
    private Future<?> future;

    @Override
    public void onClosed () {
        if (listener != null) {
            listener.onDisconnected (this);
        }
    }

    @Override
    public void onReceived (byte[] data) {
        if (listener != null) {
            listener.onReceived (data);
        }
    }

    interface TcpClientListener {
        void onConnected (TcpClientWorker worker);
        void onDisconnected (TcpClientWorker worker);
        void onReceived (byte[] data);
    }

    private TcpClientListener listener;

    TcpClientWorker (Socket socket, /*IMessageLogger messager, */ExecutorService executor, TcpClientListener listener) throws IOException {
        this.socket   = socket;

        name   = socket.getRemoteSocketAddress ().toString ();
        out    = socket.getOutputStream ();
        reader = new TcpReader (socket.getInputStream ()/*, messager*/);

        this.listener = listener;
        reader.listener = this;
        future = executor.submit (reader);
        if (listener != null) {
            listener.onConnected (this);
        }
    }

    void write (byte[] data) throws IOException {
        if (out != null) {
            out.write (data);
        }
    }

    void close () throws IOException {
        if (socket != null) {
            socket.close ();
        }
        if (future != null) {
            future.cancel (true);
        }
        if (reader != null) {
            reader.shutdown ();
        }
    }
}